package com.x.ant.manage;

import com.x.ant.dao.DeptDao;
import com.x.ant.dao.UserDao;
import com.x.ant.model.*;
import com.x.ant.util.Base64Image;
import com.x.ant.util.CodeUtil;
import com.x.framework.manage.BaseManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Service
public class DeptManage extends BaseManage {
    private final static String DEPT_LOGO_PATH = "/upload/dept/";

    @Autowired
    private DeptDao deptDao;

    @Autowired
    private UserDao userDao;

    public Dept insertDept(Dept dept) throws Exception {
        String deptParentId = dept.getDeptParentId();
        Dept parentDept = new Dept();
        parentDept.setDeptId(deptParentId);
        List<Dept> parentDeptList = deptDao.selectDeptList(parentDept);
        String parentDeptCode = null;
        if (parentDeptList.size() > 0) {
            parentDept = parentDeptList.get(0);
            parentDeptCode = parentDept.getDeptCode();
        }
        String maxCode = deptDao.selectMaxCode(deptParentId);
        String deptCode = CodeUtil.getCode(parentDeptCode, maxCode);
        dept.setDeptCode(deptCode);
        dept.setDeptCreateTime(this.getDate(0));
        String deptId = this.getUid(32);
        dept.setDeptId(deptId);

        String deptLogoBase64 = dept.getDeptLogo();
        dept.setDeptLogo(DEPT_LOGO_PATH + deptId + ".png");
        dept = this.insert(dept);

        DeptUser deptUser = new DeptUser();
        deptUser.setDeptId(deptId);

//        String userId = user.getUserId();
//        if(this.isString(userId)) {
//            deptUser.setUserId(userId);
//            this.delete(deptUser);
//        } else {
//            user.setUserCreateTime(this.getDate(0));
//            user = this.insert(user);
//
//            userId = user.getUserId();
//            Staff staff = new Staff();
//            staff.setStaffId(userId);
//            this.insert(staff);
//
//            deptUser.setUserId(userId);
//        }
//        this.insert(deptUser);

        if(this.isString(deptLogoBase64)) {
            Base64Image.generateImage(deptLogoBase64, getRealPath(DEPT_LOGO_PATH), dept.getDeptId() + ".png");
        }

        return dept;
    }

    public void updateDept(Dept dept) throws Exception {
        String deptLogoBase64 = dept.getDeptLogo();
        dept.setDeptLogo(DEPT_LOGO_PATH + dept.getDeptId() + ".png");
        this.update(dept);
        if(this.isString(deptLogoBase64)) {
            Base64Image.generateImage(deptLogoBase64, getRealPath(DEPT_LOGO_PATH), dept.getDeptId() + ".png");
        }
    }

}